package models

import (
	"github.com/astaxie/beego/orm"
)

type PqCsTestLibrary struct {
	Id int
	Title string
	Desc string
	HardRate float64
	AveragePoint int
	TestCount int
	ModuleType int
	Score int
	State int
	PqTestCategoryId int
	IsSpirit int
	SpiritStart string
	SpiritEnd string
	PqTestAreaId int
	AreaCode string
	AreaCodes string
	BaseModel
}

func (pct * PqCsTestLibrary) ListForFront(user PqUser,testCategory PqTestCategory,skip,limit int ) ([]orm.Params,interface{}) {
	var nodes []orm.Params
	model := GetSlaveDb()
	areaCode := user.AreaCode
	if testCategory.Code == "GK" {
		areaCode = ""
	}
	// 省考则找到省级code，并找到相应的真题
	if testCategory.Code == "SK" {
		var area Area
		_ = model.QueryTable(`area`).Filter("area_code", areaCode).One(&area)
		areaCode = area.ParentCode
	}
	_, _ = model.Raw(`
		select SQL_CALC_FOUND_ROWS ctl.*,cate.title as category_title from pq_cs_test_library as ctl
		inner join pq_test_category as cate on cate.id = ctl.pq_test_category_id
		where ctl.state > 0 and ctl.is_spirit = 0 and cate.lft >= ? and cate.rgt <= ? and ctl.area_code = ? order by ctl.updated_time desc
		limit ?,?
	`, testCategory.Lft,testCategory.Rgt,areaCode,skip,limit).Values(&nodes)
	var maps []orm.Params
	_, _ = model.Raw(`select count('ctl.*') as amount from pq_cs_test_library as ctl
		inner join pq_test_category as cate on cate.id = ctl.pq_test_category_id
		where ctl.state > -1 and cate.lft >= ? and cate.rgt <= ? and ctl.area_code = ?`,testCategory.Lft,testCategory.Rgt,areaCode).Values(&maps)
	amount := maps[0]["amount"]
	return nodes,amount
}
func (pct *PqCsTestLibrary) ListAll(q ... interface{}) ([]orm.Params,interface{}) {
	var nodes []orm.Params
	model := GetSlaveDb()
	_, _ = model.Raw(`
		select ctl.*,cate.title as category_title from pq_cs_test_library as ctl
		inner join pq_test_category as cate on cate.id = ctl.pq_test_category_id
		where ctl.state > ? and ctl.is_spirit = ? and cate.lft >= ? and cate.rgt <= ? order by ctl.updated_time desc
		limit ?,?
	`, q).Values(&nodes)
	var maps []orm.Params
	_, _ = model.Raw(`select count('ctl.*') as amount from pq_cs_test_library as ctl
		inner join pq_test_category as cate on cate.id = ctl.pq_test_category_id
		where ctl.state > ?`, q[0]).Values(&maps)
	amount := maps[0]["amount"]
	return nodes,amount
}

func (pct *PqCsTestLibrary) GetOne(q ... interface{}) orm.Params {
	var nodes []orm.Params
	model := GetSlaveDb()
	//qs := []interface{}{}
	//for k,v := range q{
	//	qs[k] = v
	//}
	_, _ = model.Raw(`
		select SQL_CALC_FOUND_ROWS ctl.*,cate.title as category_title,cate.point_data from pq_cs_test_library as ctl
		inner join pq_test_category as cate on cate.id = ctl.pq_test_category_id
		where ctl.id = ? and ctl.state > -1
	`, q).Values(&nodes)
	return nodes[0]
}
